<template>
  <div class="app-container">
    <!-- 搜索条件 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" size="small">
      <el-form-item label="品牌名称" prop="brandId">
        <el-select v-model="queryParams.brandId" placeholder="请选择品牌名称" clearable size="small">
          <el-option v-for="dict in brandNameList" :key="parseInt(dict.id)" :label="dict.name" :value="parseInt(dict.id)" />
        </el-select>
      </el-form-item>
      <el-form-item label="型号类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择型号类型" clearable size="small">
          <el-option v-for="dict in modelTypeList" :key="parseInt(dict.id)" :label="dict.name" :value="parseInt(dict.id)" />
        </el-select>
      </el-form-item>
      <el-form-item label="型号名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入型号名称" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="getTableData">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="small" @click="openDialog">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-upload2" size="small" @click="handleImport" v-hasPermi="['pekingfish:phonemodel:import']">导入</el-button>
        <!-- <el-upload
          class="upload-demo"
          :file-list="fileList"
          :action="uploadUrl"
          :limit="1"
          :before-upload="
            (file) => {
              return beforeUpload(file);
            }
          "
        >
          <el-button   type="primary">导入手机型号</el-button>
        </el-upload> -->
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getTableData"></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="tableData">
      <el-table-column label="操作" align="center" fixed="left" width="150">
        <template v-slot="scope">
          <el-button type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['pekingfish:phonemodel:update']">编辑</el-button>
          <el-button link type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['pekingfish:phonemodel:delete']">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column label="品牌名称" prop="brandName" align="center" fixed="left" />
      <el-table-column label="型号类型" prop="type" align="center">
        <template v-slot="scope">
          <span v-if="scope.row.type == 1">非折叠</span>
          <span v-if="scope.row.type == 2">折叠屏</span>
        </template>
      </el-table-column>
      <el-table-column label="型号名称" prop="name" align="center" />
      <el-table-column label="内存" prop="memory" align="center">
        <template v-slot="scope">
          <div v-for="(item, index) in JSON.parse(scope.row.memory)" :key="index + 'memory'">{{ item }}</div>
        </template>
      </el-table-column>
      <el-table-column label="颜色" prop="color" align="center">
        <template v-slot="scope">
          <div v-for="(item, index) in JSON.parse(scope.row.color)" :key="index + 'color'">{{ item }}</div>
        </template>
      </el-table-column>
      <el-table-column label="购买渠道" prop="buyChannel" align="center">
        <template v-slot="scope">
          <div v-for="(item, index) in JSON.parse(scope.row.buyChannel)" :key="index + 'buyChannel'">{{ item }}</div>
        </template>
      </el-table-column>
      <el-table-column label="网络制式" prop="networkType" align="center">
        <template v-slot="scope">
          <div v-for="(item, index) in JSON.parse(scope.row.networkType)" :key="index + 'networkType'">{{ item }}</div>
        </template>
      </el-table-column>
      <!-- <el-table-column label="转轴情况" prop="shaft" align="center" /> -->

    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize" @pagination="getTableData" />

    <!-- 新增/编辑 -->
    <el-dialog :title="dialogText" :visible.sync="dialogVisible" width="460px" v-dialogDrag append-to-body>
      <el-form :model="dialogParams" ref="dialogForm" :rules="rules" label-width="120px">
        <el-form-item label="品牌名称" prop="brandId">
          <el-select v-model="dialogParams.brandId" placeholder="请选择品牌名称" clearable size="small">
            <el-option v-for="dict in brandNameList" :key="parseInt(dict.id)" :label="dict.name" :value="parseInt(dict.id)" />
          </el-select>
        </el-form-item>
        <el-form-item label="型号类型" prop="type">
          <el-select v-model="dialogParams.type" placeholder="请选择型号类型" clearable size="small">
            <el-option v-for="dict in modelTypeList" :key="parseInt(dict.id)" :label="dict.name" :value="parseInt(dict.id)" />
          </el-select>
        </el-form-item>
        <el-form-item label="型号名称" prop="name">
          <el-input style="width: 200px" v-model="dialogParams.name" placeholder="请输入型号名称" clearable />
        </el-form-item>
        <el-form-item v-for="(item, index) in dialogParams.memory" :label="'内存' + (index + 1)" :key="index + 'memory'" prop="memory">
          <el-input style="width: 200px" v-model="item.name" placeholder="请输入内存" clearable />
          <i @click="addDialogParams('memory')" title="添加" v-if="index == dialogParams.memory.length - 1" style="margin-left: 10px; cursor: pointer" class="el-icon-circle-plus-outline"></i>
          <i @click="delParams('memory',dialogParams.memory,item)" title="移除" v-if="index >0" style="margin-left: 10px; cursor: pointer;color:#ff0000" class="el-icon-circle-close"></i>
        </el-form-item>
        <el-form-item v-for="(item, index) in dialogParams.color" :label="'颜色' + (index + 1)" :key="index + 'color'" prop="color">
          <el-input style="width: 200px" v-model="item.name" placeholder="颜色" clearable />
          <i @click="addDialogParams('color')" title="添加" v-if="index == dialogParams.color.length - 1" style="margin-left: 10px; cursor: pointer" class="el-icon-circle-plus-outline"></i>
          <i @click="delParams('color',dialogParams.color,item)" title="移除" v-if="index >0" style="margin-left: 10px; cursor: pointer;color:#ff0000" class="el-icon-circle-close"></i>
        </el-form-item>
        <el-form-item v-for="(item, index) in dialogParams.buyChannel" :label="'购买渠道' + (index + 1)" :key="index + 'buyChannel'" prop="buyChannel">
          <el-input style="width: 200px" v-model="item.name" placeholder="请输入购买渠道" clearable />
          <i @click="addDialogParams('buyChannel')" title="添加" v-if="index == dialogParams.buyChannel.length - 1" style="margin-left: 10px; cursor: pointer" class="el-icon-circle-plus-outline"></i>
          <i @click="delParams('buyChannel',dialogParams.buyChannel,item)" title="移除" v-if="index >0" style="margin-left: 10px; cursor: pointer;color:#ff0000" class="el-icon-circle-close"></i>
        </el-form-item>
        <el-form-item v-for="(item, index) in dialogParams.networkType" :label="'网络制式' + (index + 1)" :key="index + 'networkType'" prop="networkType">
          <el-input style="width: 200px" v-model="item.name" placeholder="请输入网络制式" clearable />
          <i @click="addDialogParams('networkType')" title="添加" v-if="index == dialogParams.networkType.length - 1" style="margin-left: 10px; cursor: pointer" class="el-icon-circle-plus-outline"></i>
          <i @click="delParams('networkType',dialogParams.networkType,item)" title="移除" v-if="index >0" style="margin-left: 10px; cursor: pointer;color:#ff0000" class="el-icon-circle-close"></i>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="confirmDialog('dialogForm')">确 定</el-button>
      </span>
    </el-dialog>
    <importUploadFile :visible.sync="visibleImportFile" :fetchFun="fetchFunImport" :importTemplate="importTemplate" @done="getTableData" templateTitle="手机型号模板" />
  </div>
</template>

<script>
import {
  getAllPhoneBrand,
  getPhoneModelTable,
  addPhoneModelInfo,
  deletePhoneModelInfo,
  importPhoneModelList,
  editPhoneModelInfo,
  importPhoneModelTemplate
} from "@/api/configuration/phoneModel";
import importUploadFile from "@/components/importUploadFile";
export default {
  name: "phoneModel",
  components: {
    importUploadFile
  },
  data() {
    return {
      visibleImportFile: false,
      fetchFunImport: importPhoneModelList,
      importTemplate: importPhoneModelTemplate,
      // 显示搜索条件
      showSearch: true,
      queryParams: {
        pageNo: 1,
        pageSize: 10,
      },
      brandNameList: [],
      modelTypeList: [
        { name: "非折叠", id: 1 },
        { name: "折叠屏", id: 2 },
      ],
      loading: false,
      tableData: [],
      total: 0,
      dialogVisible: false,
      dialogText: "新增",
      dialogParams: {
        memory: [{ name: "" }],
        color: [{ name: "" }],
        buyChannel: [{ name: "" }],
        networkType: [{ name: "" }],
      },
      rules: {
        brandId: [
          { required: true, message: "请选择品牌名称", trigger: "change" },
        ],
        type: [
          { required: true, message: "请选择型号类型", trigger: "change" },
        ],
        name: [{ required: true, message: "请输入型号名称", trigger: "blur" }],
        memory: [{ required: true, message: "请输入内存", trigger: "blur" }],
        color: [{ required: true, message: "请输入颜色", trigger: "blur" }],
        buyChannel: [
          { required: true, message: "请输入购买渠道", trigger: "blur" },
        ],
        networkType: [
          { required: true, message: "请输入网络制式", trigger: "blur" },
        ],
      },
      fileList: [],
      uploadUrl:
        process.env.VUE_APP_BASE_API + "/admin-api/" + "infra/file/upload",
    };
  },
  created() {
    this.getBrandNameList();
    this.getTableData();
  },
  methods: {
    async getBrandNameList() {
      const { data } = await getAllPhoneBrand();
      this.brandNameList = data;
    },
    async getTableData() {
      const { data } = await getPhoneModelTable(this.queryParams);
      this.tableData = data.list;
      this.total = data.total;
    },
    resetQuery() {
      this.queryParams = {
        pageNo: 1,
        pageSize: 10,
      };
      this.getTableData()
    },
    rest() {
      this.dialogParams = {
        brandId: undefined,
        type: undefined,
        name: undefined,
        memory: [{ name: "" }],
        color: [{ name: "" }],
        buyChannel: [{ name: "" }],
        networkType: [{ name: "" }],
      }
      this.resetForm("dialogForm");
    },
    openDialog() {
      this.dialogVisible = true;
      this.dialogText = "新增";
      this.rest()
    },
    beforeUpload(data) {

      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const formData = new FormData();
      formData.append("file", file);
      importPhoneModelList(formData).then((res) => {
        console.log(res, "ffff");
      });
    },
    handleUpdate(data) {
      this.rest()
      this.dialogVisible = true;
      this.dialogText = "编辑";
      this.dialogParams = {
        ...data,
        buyChannel: JSON.parse(data.buyChannel).map((el) => {
          return { name: el };
        }),
        color: JSON.parse(data.color).map((el) => {
          return { name: el };
        }),
        memory: JSON.parse(data.memory).map((el) => {
          return { name: el };
        }),
        networkType: JSON.parse(data.networkType).map((el) => {
          return { name: el };
        }),
      };
    },
    handleDelete(data) {
      this.$confirm("确定要删除当前数据吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deletePhoneModelInfo([data.id]).then((res) => {
            // console.log(res, "fff");
            if (res.data) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getTableData();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    addDialogParams(data) {
      this.dialogParams[data].push({ name: "" });
    },
    confirmDialog(data) {
      this.$refs[data].validate((valid) => {
        if (valid) {
          const params = {
            ...this.dialogParams,
            buyChannel: JSON.stringify(
              this.dialogParams.buyChannel.map((el) => {
                return el.name;
              })
            ),
            color: JSON.stringify(
              this.dialogParams.color.map((el) => {
                return el.name;
              })
            ),
            memory: JSON.stringify(
              this.dialogParams.memory.map((el) => {
                return el.name;
              })
            ),
            networkType: JSON.stringify(
              this.dialogParams.networkType.map((el) => {
                return el.name;
              })
            ),
          };
          this.loading = true;
          if (this.dialogText == "新增") {
            addPhoneModelInfo(params).then((res) => {
              // console.log(res, "ffff");
              if (res.data) {
                this.dialogVisible = false;
                this.$message({
                  message: "操作成功",
                  type: "success",
                });
                this.getTableData();
              }
              this.loading = false
            }).catch(f => {
              this.loading = false
            })
          }
          if (this.dialogText == "编辑") {
            editPhoneModelInfo(params).then((res) => {
              if (res.data) {
                this.dialogVisible = false;
                this.$message({
                  message: "操作成功",
                  type: "success",
                });
                this.getTableData();
              }
              this.loading = false
            }).catch(f => {
              this.loading = false
            })
          }
        }
      });
    },
    handleImport() {
      this.visibleImportFile = true
    },
    delParams(type, list, item) {
      this.$confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let index = list.indexOf(item);
        if (index != -1) {
          list.splice(index, 1)
        }
      });
    }
  },
};
</script>
<style lang="scss" scoped></style>
